#include "Sock.hpp"
#include "Protocol.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " ip port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    int sockfd = Sock::Socket();
    //连接服务器
    Sock::Connect(sockfd, argv[1], atoi(argv[2]));

    // std::cout << "Please Enter #" << std::endl;
    while (true)
    {
        Request_t req;
        memset(&req, 0, sizeof(req));
        //输入X
        std::cout << "Plesase input left operator number" << std::endl;
        std::cin >> req.x;

        //输入Y
        std::cout << "Plesase input right operator number" << std::endl;
        int y;
        std::cin >> req.y;

        //输入operation
        std::cout << "Plesase input operator" << std::endl;
        char op;
        std::cin >> req.op;

        // Json串，序列化请求
        std::string send_string = SerializeRequest(req);
        ssize_t s = send(sockfd, send_string.c_str(), send_string.size(), 0);
        // ssize_t s = send(sockfd, &req, sizeof(req), 0);

        char buffer[1024];
        //读取结果
        s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (s > 0)
        {
            buffer[s] = 0;
            std::string json_string = buffer;
            Response_t rep;
            //反序列化
            DeserializeResponse(json_string, rep);

            if (rep.code == 0)
                printf("%d %c %d = %d\n", req.x, req.op, req.y, rep.res);
            else
                printf("error\n");
        }
        else
            break;
        // char buffer[1024];
        // s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        // if(s > 0){
        //     buffer[s] = 0;
        //     std::cout << buffer << std::endl;
        // }
        //  else break;
        // std::string send_string;
        // std::cin >> send_string;
        // struct sockaddr_in tmp;
        // ssize_t size = sendto(sockfd, send_string.c_str(), send_string.size(), 0, (struct sockaddr *)&tmp, sizeof(tmp));

        // char buffer[1024];
        // size = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        // if (size > 0)
        // {
        //     buffer[size] = 0;
        //     std::cout << "Server get->" << buffer << std::endl;
        // }
        // else
        //     break;
    }

    close(sockfd);
    return 0;
}